<template>
    <el-row :gutter="2">
        <el-col :col="24" style="display: flex;justify-content: space-between; margin-bottom: 10px;">
            <el-space :size="2" wrap>
                <el-input v-model="search" placeholder="搜索" style="max-width: 300px;" />
                <el-button :icon="Search" @click="SearchHandler" plain />
            </el-space>
            <el-button :icon="Refresh" @click="RefreshTable" plain />
        </el-col>
        <el-col :span="24">
            <el-table :data="TableData" max-height="68vh" v-loading="loading"
                :header-cell-style="{ background: '#f4f6f8' }">
                <el-table-column type="expand">
                    <template #default="props">
                        <div style="padding: 20px;">
                            <el-descriptions title="详细信息" :column="2" direction="vertical">
                                <el-descriptions-item label="封面" :span="2">
                                    <el-image lazy class="cover"
                                        :src="!props.row.cover ? 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg' : props.row.cover"
                                        fit="fill">
                                        <template #error>
                                            <div class="image-slot">
                                                <el-icon><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </el-descriptions-item>
                                <el-descriptions-item label="中文名">
                                    <h3>{{ props.row.c_name ? props.row.c_name : '未知' }}</h3>
                                </el-descriptions-item>
                                <el-descriptions-item label="原名">
                                    <h3>{{ props.row.galname ? props.row.galname : '未知' }}</h3>
                                </el-descriptions-item>
                                <el-descriptions-item label="简介" :span="2">{{ props.row.intro }}</el-descriptions-item>
                                <el-descriptions-item label="会社">
                                    <a href="#">{{ props.row.company ? props.row.company : "未知" }}</a>
                                </el-descriptions-item>
                                <el-descriptions-item label="发布时间">{{ props.row.premiere }}</el-descriptions-item>
                                <el-descriptions-item label="发售时间">{{ props.row.issue_time }}</el-descriptions-item>
                                <el-descriptions-item label="文件编号">
                                    {{ props.row.number }}
                                </el-descriptions-item>
                                <el-descriptions-item label="百度网盘">
                                    <a :href="props.row.address" target="_blank">
                                        <el-button type="primary">
                                            查看
                                        </el-button>
                                    </a>
                                </el-descriptions-item>
                                <el-descriptions-item label="提取码">
                                    {{ props.row.pwd }}
                                </el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <el-rate v-model="props.row.rate" disabled allow-half show-score
                                        text-color="#ff9900" score-template="{value} 分" />
                                </el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <el-divider content-position="left">
                                        <h3>角色信息</h3>
                                    </el-divider>
                                </el-descriptions-item>
                                <div v-for="item in props.row.content" :key="item">
                                    <el-descriptions-item>
                                        <el-image lazy class="roles_avatar"
                                            :src="!item.avatar ? 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg' : item.avatar"
                                            fit="fill">
                                            <template #error>
                                                <div class="image-slot">
                                                    <el-icon><icon-picture /></el-icon>
                                                </div>
                                            </template>
                                        </el-image>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <el-space fill direction="vertical" wrap>
                                            <span>
                                                <a href="#">{{ item.nickname }}({{ item.name }})</a>
                                            </span>
                                            <span>
                                                性别： {{
        item.gender === 0 ? '男' :
            item.gender === 1 ? '女' : '未知'
    }}
                                            </span>
                                            <span>
                                                配音：<a href="#">{{ item.voice_actor }}</a>
                                            </span>
                                            <span>
                                                {{ item.intro }}
                                            </span>
                                        </el-space>
                                    </el-descriptions-item>
                                </div>
                                <el-descriptions-item :span="2">
                                    <el-divider content-position="left">
                                        <h3>OP</h3>
                                    </el-divider>
                                </el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <video width="400" height="240" controls>
                                        <!-- <source :src="props.row.op" type="video/mp4"> -->
                                    </video>
                                </el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <el-divider content-position="left">
                                        <h3>CG</h3>
                                    </el-divider>
                                </el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <n-upload action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                                        :default-file-list="fileList" list-type="image-card">
                                        点击上传
                                    </n-upload>
                                </el-descriptions-item>
                                <!-- <el-descriptions-item :span="2">
                                    <el-divider content-position="left">
                                        <h3>相关游戏</h3>
                                    </el-divider>
                                </el-descriptions-item>
                                <el-descriptions-item>
                                    <el-space :size="10" wrap>
                                        <Card :url="props.row.cover" link="" :name="props.row.c_name" />
                                    </el-space>
                                </el-descriptions-item> -->
                            </el-descriptions>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="游戏名" :header-cell-class-name="'custom-header'">
                    <template #default="{ row }">
                        <el-text truncated>
                            {{ row.c_name }}
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column label="所属地区" prop="country" :header-cell-class-name="'custom-header'" />
                <el-table-column label="评分" prop="rate" width="60" :header-cell-class-name="'custom-header'" />
                <el-table-column label="创建人" prop="creator" width="140" align="center"
                    :header-cell-class-name="'custom-header'" />
                <el-table-column label="创建时间" prop="create" width="160" align="center"
                    :header-cell-class-name="'custom-header'" />
                <el-table-column label="操作" width="300" fixed="right" align="center"
                    :header-cell-class-name="'custom-header'">
                    <template #default="{ row }">
                        <el-space :size="10" wrap>
                            <el-switch v-model="row.is_show" inline-prompt active-text="展示" inactive-text="隐藏"
                                :active-value="0" :inactive-value="1"
                                style="--el-switch-on-color:  #13ce66; --el-switch-off-color: #ff4949"
                                :loading="loadingSwitch[row.id]" :before-change="() => beforeChange(row)" />
                            <el-button type="warning" :icon="Edit" @click="Dialog(row)" link>修改</el-button>
                            <el-button type="danger" :icon="Delete" @click="SoftDelHandler(row)" link>删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无数据" />
                </template>
            </el-table>
        </el-col>
        <el-col :span="24">
            <el-pagination v-model:currentPage="currentPage" :page-sizes="[20, 40, 80, 100]"
                v-model:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" hide-on-single-page
                class="pagination" />
        </el-col>

        <el-dialog v-model="dialogFormVisible" width="40%" title="修改词条">
            <el-form :model="selectedRow" :rules="rules" label-width="auto" ref="changeRoutesRuleRef">
                <el-form-item label="原名" prop="galname">
                    <el-input v-model="selectedRow.galname" clearable required />
                </el-form-item>
                <el-form-item label="中文名" prop="c_name">
                    <el-input v-model="selectedRow.c_name" clearable required />
                </el-form-item>
                <el-form-item label="地区" prop="country">
                    <el-radio-group v-model="selectedRow.country">
                        <el-radio label="中国" :value="0"></el-radio>
                        <el-radio label="日本" :value="1"></el-radio>
                        <el-radio label="欧美" :value="2"></el-radio>
                        <el-radio label="其他" :value="3"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-row style="display: flex; justify-content: space-between;">
                    <el-form-item label="发布时间">
                        <el-date-picker v-model="selectedRow.premiere" type="date" placeholder="选择日期"
                            format="YYYY年MM月DD日" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="发售时间">
                        <el-date-picker v-model="selectedRow.issue_time" type="date" placeholder="选择日期"
                            format="YYYY年MM月DD日" value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-row>
                <el-form-item label="简介" prop="intro">
                    <el-input v-model="selectedRow.intro" :rows="4" maxlength="2000" type="textarea" show-word-limit
                        clearable required />
                </el-form-item>
                <el-row style="display: flex; justify-content: space-between;">
                    <el-form-item label="链接地址" prop="address">
                        <el-input v-model="selectedRow.address" clearable required />
                    </el-form-item>
                    <el-form-item label="提取码" prop="pwd">
                        <el-input v-model="selectedRow.pwd" style="width: 80px" clearable required />
                    </el-form-item>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="UpdateHandler(changeRoutesRuleRef)">
                    修改
                </el-button>
            </template>
        </el-dialog>
    </el-row>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { ElSpace, ElDescriptions, ElInput, ElText, ElDivider, ElTag, ElButton, ElSwitch, ElDescriptionsItem, ElRow, ElCol, ElTable, ElTableColumn, ElEmpty, ElPagination } from 'element-plus';
import { Edit, Delete, Refresh, Search, Picture as IconPicture } from '@element-plus/icons-vue';
import { NUpload } from 'naive-ui';
import { Info, SearchGalInfo, IsShow, SoftDel, Update } from '@/Apis/modules/galgame';
import GalStore from '@/stores/modules/GalStore'

const showModal = ref(false);
const previewImageUrl = ref('');
const handlePreview = (file) => {
    const { url } = file;
    previewImageUrl.value = url;
    showModal.value = true;
};

const fileList = ([
    {
        id: 1,
        name: 'ATRI_1.jpg',
        status: "finished",
        url: 'http://localhost:3000/api/files/images/CG/ATRI_1.jpg',
    },
    {
        id: 2,
        name: 'ATRI_2.jpg',
        status: "finished",
        url: 'http://localhost:3000/api/files/images/CG/ATRI_2.jpg',
    },
    {
        id: 3,
        name: 'ATRI_3.jpg',
        status: "finished",
        url: 'http://localhost:3000/api/files/images/CG/ATRI_3.png',
    },
    {
        id: 4,
        name: 'ATRI_4.jpg',
        status: "finished",
        url: 'http://localhost:3000/api/files/images/CG/ATRI_4.jpeg',
    },
    {
        id: 5,
        name: 'ATRI_5.jpg',
        status: "finished",
        url: 'http://localhost:3000/api/files/images/CG/ATRI_5.jpg',
    },
])


// 获取数据
onMounted(async () => await GetAnimeInfo());

const store = GalStore();
const search = ref('');
const loading = ref(false)        // 懒加载赋值
const currentPage = ref(1);       // 当前页码
const pageSize = ref(20);         // 每页显示的数据条
const totalItems = ref(0);        // 总数据条数
// 分页
const handleSizeChange = (val) => {
    pageSize.value = val;         // 更新每页显示的数据条数
    currentPage.value = 1;        // 重置当前页码为第一页
}
const handleCurrentChange = (val) => {
    currentPage.value = val;      // 更新当前页码
}

const normal = ref(0)

// 动态渲染页面并筛选
const TableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;

    return store.info.slice(start, end);
});

// 异步获取数据
const GetAnimeInfo = async () => {
    loading.value = true;
    setTimeout(async () => {
        await Info();
        loading.value = false;
    }, 1000)
}

// 搜索
const SearchHandler = async () => {
    if (!search.value) return ElMessage.error("请输入关键词");
    await SearchGalInfo(search.value);
}

// 刷新
const RefreshTable = async () => { await GetAnimeInfo() };

// 对话框控制
const dialogFormVisible = ref(false)
const Dialog = (row) => {
    // 使用展开运算符来创建一个新的对象，避免直接修改原始数据
    selectedRow.value = { ...row };
    dialogFormVisible.value = true;
}

// 重置表单
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisible.value = false
}

// 验证规则
const rules = ref({
    galname: [{ required: true, trigger: 'blur' }],
    c_name: [{ trigger: 'blur' }],
    country: [{ required: true, trigger: 'blur' }],
    premiere: [{ trigger: 'blur' }],
    issue_time: [{ trigger: 'blur' }],
    intro: [{ required: true, trigger: 'blur' }],
    address: [{ required: true, trigger: 'blur' }],
    pwd: [{ required: true, trigger: 'blur' }],
})

// 更新
const changeRoutesRuleRef = ref();
const selectedRow = ref({
    galname: null,
    c_name: null,
    country: null,
    premiere: null,
    issue_time: null,
    intro: null,
    address: null,
    pwd: null,
});

const UpdateHandler = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const { id, path, name, icon, title } = selectedRow.value;
            const data = { id, path, name, icon, title };

            await Update(data);
            dialogFormVisible.value = false
        } else {
            return ElMessage.error('验证未通过!')
        }
    })
}

// 是否展示
const loadingSwitch = reactive({});
const beforeChange = (row) => {
    const data = {
        id: row.id,
        is_show: row.is_show === 0 ? 1 : 0
    }
    loadingSwitch[row.id] = true;
    return new Promise(async (resolve) => {
        await IsShow(data).then(() => {
            setTimeout(async () => {
                loadingSwitch[row.id] = false
                return resolve(true);
            }, 1000)
        }).catch((error) => {
            loadingSwitch[row.id] = false;
            ElMessage.error('切换失败');
        })
    })
}


// 软删除
const SoftDelHandler = (row) => {
    const data = {
        id: row.id,
        is_delete: 1,
    };
    ElMessageBox.confirm(
        '是否删除该词条?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 发起删除请求
            SoftDel(data).then(() => {
                const index = store.info.findIndex(item => item.id === data.id);
                if (index !== -1) {
                    store.info.splice(index, 1);
                }
            });
        })
        .catch(() => {
            return
        })
}
</script>

<style scoped>
.pagination {
    display: flex;
    justify-content: center;
    margin: 10px 0;
}

.cover {
    max-width: 1000px;
    max-height: 1000px;
    border-radius: 4px;
}

.roles_avatar {
    max-width: 400px;
    max-height: 400px;
    border-radius: 4px;
    display: flex;
    justify-content: center;
}

.dialog-footer {
    display: flex;
    justify-content: right;
}
</style>